package com.hub.service.asset.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hub.service.impl.BaseServiceImpl;
import com.hub.dto.asset.AssetInfoDto;
import com.hub.dto.asset.AssetInfoFileDto;
import com.hub.dto.asset.SearchAssetInfoDto;
import com.hub.entity.asset.AssetBrandInfo;
import com.hub.entity.asset.AssetCategoryInfo;
import com.hub.entity.asset.AssetInfoEntity;
import com.hub.frame.consts.ConstantUtil;
import com.hub.model.asset.AssetInfoFileModel;
import com.hub.service.asset.IAssetInfoFilesService;
import com.hub.utils.ApiResultObject;
import com.hub.utils.PagingResultObject;
import com.hub.utils.enums.FileTypeEnum;
import com.hub.utils.enums.UnitEnum;
import com.hub.mapper.asset.AssetInfoMapper;
import com.hub.model.asset.AssetInfoModel;
import com.hub.service.asset.IAssetBrandInfoService;
import com.hub.service.asset.IAssetInfoService;
import com.hub.service.asset.ICategoryInfoService;
import org.apache.commons.lang3.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hub
 * @since 2020-05-18
 */
@Service
public class AssetInfoServiceImpl extends BaseServiceImpl<AssetInfoMapper, AssetInfoEntity> implements IAssetInfoService {

    @Autowired
    private Mapper mapper;

    @Autowired
    private IAssetBrandInfoService assetBrandInfoService;

    @Autowired
    private ICategoryInfoService categoryInfoService;

    @Autowired
    private IAssetInfoFilesService assetInfoFilesService;


    /**
     * 根据条件查询资产基础信息
     * @param request
     * @return
     */
    public PagingResultObject searchAssetInfoList(SearchAssetInfoDto request)
    {

        request.setPageIndex( request.getPageIndex() > 0 ? request.getPageIndex() : 1);
        request.setPageSize(request.getPageSize() > 0?request.getPageSize():20);

        //查询条件
        QueryWrapper<AssetInfoEntity> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(request.getName())){
            wrapper.like("name", request.getName());
        }
        if(request.getBrandId() > 0){
            wrapper.eq("brand_id", request.getBrandId());
        }
        if(StringUtils.isNotEmpty(request.getMainCategoryCode())){
            wrapper.eq("main_category_code", request.getMainCategoryCode());
        }
        if(StringUtils.isNotEmpty(request.getSmallCategoryCode())){
            wrapper.eq("small_category_code", request.getSmallCategoryCode());
        }
        if(StringUtils.isNotEmpty(request.getModel())){
            wrapper.like("model", request.getModel());
        }
        wrapper.eq("active_flg", ConstantUtil.YES);

        IPage<AssetInfoEntity> result = baseMapper.selectPage(new Page<>(request.getPageIndex(), request.getPageSize()), wrapper);
        List<AssetInfoModel> modelList = new ArrayList<AssetInfoModel>();
        List<AssetInfoEntity> resultList = result.getRecords();
        for (AssetInfoEntity entity: resultList) {
            AssetInfoModel model = mapper.map(entity, AssetInfoModel.class);

            AssetBrandInfo brand = assetBrandInfoService.getById(model.getBrandId());
            if(brand != null) {
                model.setBrandName(brand.getBrandName());
            }

            AssetCategoryInfo mainCategory = categoryInfoService.getMainCategoryByCode(entity.getMainCategoryCode());
            if(mainCategory != null) {
                model.setMainCategoryName(mainCategory.getCategoryName());
            }

            AssetCategoryInfo smallCategory = categoryInfoService.getCategoryByParentCodeAndCode(entity.getMainCategoryCode(), entity.getSmallCategoryCode());
            if(smallCategory != null) {
                model.setSmallCategoryName(smallCategory.getCategoryName());
            }

            List<AssetInfoFileModel> fileList = assetInfoFilesService.loadAssetFilesByAssetId(entity.getId());
            List<AssetInfoFileModel> pictureFileList = new ArrayList<>();
            List<AssetInfoFileModel> maintenanceFileList = new ArrayList<>();
            List<AssetInfoFileModel> knowledgeFileList = new ArrayList<>();

            for (AssetInfoFileModel file: fileList) {
                if(file.getFileType() == FileTypeEnum.Picture.getCode())
                    pictureFileList.add(file);
                else if(file.getFileType() == FileTypeEnum.Maintenance.getCode())
                    maintenanceFileList.add(file);
                else if(file.getFileType() == FileTypeEnum.Knowledge.getCode())
                    knowledgeFileList.add(file);
            }
            model.setPictureFileItems(pictureFileList);
            model.setMaintenanceFileItems(maintenanceFileList);
            model.setKnowledgeFileItems(knowledgeFileList);

            modelList.add(model);
        }

        return PagingResultObject.success(modelList,request.getPageIndex(),request.getPageSize(),result.getTotal());
    }

    /**
     *根据ID获取资产基础信息
     * @param id
     * @return
     */
    public ApiResultObject getAssetInfoDetail(Long id) {

        AssetInfoEntity entity = this.getBaseMapper().selectById(id);
        if(entity != null)
        {
            AssetInfoModel model = mapper.map(entity,AssetInfoModel.class);
            //获取名称
            AssetBrandInfo brand = assetBrandInfoService.getById(model.getBrandId());
            if(brand != null) {
                model.setBrandName(brand.getBrandName());
            }

            AssetCategoryInfo mainCategory = categoryInfoService.getMainCategoryByCode(entity.getMainCategoryCode());
            if(mainCategory != null) {
                model.setMainCategoryName(mainCategory.getCategoryName());
            }

            AssetCategoryInfo smallCategory = categoryInfoService.getCategoryByParentCodeAndCode(entity.getMainCategoryCode(), entity.getSmallCategoryCode());
            if(smallCategory != null) {
                model.setSmallCategoryName(smallCategory.getCategoryName());
            }

            if(entity.getUnit() > 0) {
                model.setUnitName(UnitEnum.getDescription((entity.getUnit())));
            }

            List<AssetInfoFileModel> fileList = assetInfoFilesService.loadAssetFilesByAssetId(entity.getId());
            List<AssetInfoFileModel> pictureFileList = new ArrayList<>();
            List<AssetInfoFileModel> maintenanceFileList = new ArrayList<>();
            List<AssetInfoFileModel> knowledgeFileList = new ArrayList<>();

            for (AssetInfoFileModel file: fileList) {
                if(file.getFileType() == FileTypeEnum.Picture.getCode())
                    pictureFileList.add(file);
                else if(file.getFileType() == FileTypeEnum.Maintenance.getCode())
                    maintenanceFileList.add(file);
                else if(file.getFileType() == FileTypeEnum.Knowledge.getCode())
                    knowledgeFileList.add(file);
            }
            model.setPictureFileItems(pictureFileList);
            model.setMaintenanceFileItems(maintenanceFileList);
            model.setKnowledgeFileItems(knowledgeFileList);

            return ApiResultObject.success(model);

        }
        return ApiResultObject.failed("未查询到对应资产基础信息");
    }

    /**
     * 新增资产基础信息
     * @param request
     * @return
     */
    @Transactional
    public ApiResultObject addAssetInfo(AssetInfoDto request) {
        //检验资产信息是否存在
        QueryWrapper<AssetInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("code",request.getCode() ).or().eq("name",request.getName());
        wrapper.eq("active_flg", ConstantUtil.YES);
        if(this.count(wrapper) > 0){
            return ApiResultObject.failed("资产主码已存在，无法保存,请重新输入！");
        }

        //保存数据库
        AssetInfoEntity entity = mapper.map(request, AssetInfoEntity.class);
//        String userName = this.getUserName();
//        entity.setCreateTime(DateUtils.getNow());
//        entity.setCreateUser(userName);
//        entity.setModifyTime(DateUtils.getNow());
//        entity.setModifyUser(userName);
//        entity.setActiveFlg(ConstantUtil.YES);
//        long id = baseMapper.insert(entity);
        if(this.save(entity)){
            if(!request.getPictureFileItems().isEmpty() ) {
                for (AssetInfoFileDto file:request.getPictureFileItems()) {
                    file.setAssetId(entity.getId());
                }
                assetInfoFilesService.addAssetInfoFiles(request.getPictureFileItems());
            }

            if(!request.getMaintenanceFileItems().isEmpty() ) {
                for (AssetInfoFileDto file:request.getMaintenanceFileItems()) {
                    file.setAssetId(entity.getId());
                }
                assetInfoFilesService.addAssetInfoFiles(request.getMaintenanceFileItems());
            }

            if(!request.getKnowledgeFileItems().isEmpty() ) {
                for (AssetInfoFileDto file:request.getKnowledgeFileItems()) {
                    file.setAssetId(entity.getId());
                }
                assetInfoFilesService.addAssetInfoFiles(request.getKnowledgeFileItems());
            }

            return ApiResultObject.success("新增资产基础信息成功!");
        }
        return ApiResultObject.failed("资产信息保存数据库失败!");
    }

    /**
     * 修改资产基础信息
     * @param request
     * @return
     */
    public ApiResultObject modifyAssetInfo(AssetInfoDto request) {
        //检验资产信息是否存在
        QueryWrapper<AssetInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("code",request.getCode() )
                .eq("id",request.getId())
                .eq("active_flg", ConstantUtil.YES);
        if(this.count(wrapper) == 0){
            return ApiResultObject.failed("资产不存在，无法保存！");
        }

        //保存数据库
        AssetInfoEntity entity = mapper.map(request, AssetInfoEntity.class);
        if(this.updateById(entity)){
            return ApiResultObject.success("修改资产基础信息成功!");
        }
        return ApiResultObject.failed("资产信息保存数据库失败!");
    }

    /**
     * 删除资产基础信息-逻辑删除
     * @param id
     * @return
     */
    public ApiResultObject removeAssetInfo(Long id) {

        if(id< 1)
            return ApiResultObject.failed("参数异常: 资产信息ID异常!");

        if(this.removeById(id)){
            return ApiResultObject.success("资产基础信息删除成功!");
        }
        return ApiResultObject.failed("资产基础信息异常，删除失败!");
    }

}
